const redis = require('redis');
const redisOptions = require('../db/redisOptions.js')

const port = redisOptions.port;
const host = redisOptions.host;
/**
 * 设置值,并设置过期时间
 * @param {String} key 键
 * @param {String} value 值
 * @param {Number} expire 过期时间(单位: 秒)
 */
const redisSet = async (key, value, expire) => {
    const client = redis.createClient();
    await client.connect(port, host).then(async () => {
        await client.set(key, value).then((val) => {
            // console.log(val);
            // 相对过期时间，最后一次调用后开始计时
            client.expire(key, expire);
            client.quit();
        })
    })
}

/**
 * 获取值
 * @param {String} key 键
 */
const redisGet = async (key) => {
    const client = redis.createClient();
    let value;
    await client.connect(port, host).then(async () => {
        await client.get(key).then((val) => {
            value = val;
            client.quit();
        })
    })
    return value;
}
module.exports = {
    redisSet,
    redisGet
}